const xml2js = require("xml2js");
const sipUtils = require("../../../utils/sipUtils");

const log4js = require('../../../utils/logUtils');
const logger = log4js.getLogger('sip');
const config = require("../../../db/config");
const settingModel = require("../../../model/setting");
const dbHandler = require("../../../service/dbhandler");

/**
 * 生成查询录像的命令
 */
const TAG = "[recordFactory]";
module.exports={
    generate: async function (deviceId, channelId, startTime, endTime, SN) {
        let callId = Math.round((new Date()).getTime() / 1000) + '';
        const deviceInfo = await dbHandler.loadDevice(deviceId);

        const json = {
            Query: {
                CmdType: 'RecordInfo',
                SN,
                DeviceID: channelId,
                StartTime: startTime,
                EndTime: endTime
            }
        };
        const builder = new xml2js.Builder({
            xmldec: {
                'version': '1.0',
                'encoding': 'GB2312',
                'standalone': null
            }
        });
        const content = builder.buildObject(json) + '\r\n\r\n';

        let cseq = {};
        cseq.method = 'MESSAGE';
        cseq.seq = 20;

        const sipSetting = await settingModel.load();
        let from = {
            name: undefined,
            uri: `sip:${sipSetting.sip_command_account}@${sipSetting.server_realm}`,
            params: {tag: sipUtils.rstring()}
        };
        let to = {
            name: undefined,
            uri: `sip:${deviceId}@${sipSetting.server_realm}`
        };
        let host = deviceInfo.sip_command_host;
        let port = deviceInfo.sip_command_port;

        logger.info(TAG, "参数调试 host=", host, ", port=", port, ", deviceId=", deviceId, ", channelId=", channelId, ", startTime=", startTime, ", endTime=", endTime,
            ", deviceInfo=", deviceInfo, ", sipSetting=", sipSetting);
        let uri = sipUtils.generateUri(deviceId, null, null, host, port);
        let via = sipUtils.generateVia(deviceInfo.protocol, null, null);
        return {
            method: cseq.method, uri, version: config.sip.version,
            headers: {
                via, from, to, cseq,
                'call-id': callId,
                'Content-Type': 'Application/MANSCDP+xml',
                'expires': '3600',
                'Max-Forwards': 70,
                'User-Agent': config.sip.useragent
            }, content
        };
    },
};
